package com.vitalfit.controller;

import com.vitalfit.enums.FileType;
import com.vitalfit.enums.ResultEnum;
import com.vitalfit.model.dto.FoodCategoryDTO;
import com.vitalfit.model.entity.food.FoodCategory;
import com.vitalfit.model.vo.FoodCategoryPageVO;
import com.vitalfit.model.vo.ResultVO;
import com.vitalfit.service.serviceImpl.FoodCategoryServiceImpl;
import com.vitalfit.utils.AliYunOSSUtil;
import com.vitalfit.utils.ResultVOUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/food-categories")
@Validated
@RequiredArgsConstructor
public class FoodCategoryController {

    private final FoodCategoryServiceImpl foodCategoryService;

    private final AliYunOSSUtil aliYunOSSUtil;


    // 添加新的食品类别
    @PreAuthorize("hasRole('ROLE_SHOPMANAGER')")
    @PostMapping
    public ResultVO<FoodCategory> addCategory(@Valid @RequestBody FoodCategoryDTO foodCategoryDTO) {
        FoodCategory createdCategory = foodCategoryService.addCategory(foodCategoryDTO);
        return ResultVOUtil.buildResult(ResultEnum.POST_SUCCESS,createdCategory);
    }

    // 更新现有的食品类别
    @PreAuthorize("hasRole('ROLE_SHOPMANAGER')")
    @PutMapping
    public ResultVO<FoodCategory> updateCategory(@Valid @RequestBody FoodCategoryDTO foodCategoryDTO) {
        FoodCategory updatedCategory = foodCategoryService.updateCategory(foodCategoryDTO);
        return ResultVOUtil.buildResult(ResultEnum.PUT_SUCCESS,updatedCategory);
    }

    // 获取特定ID的食品类别
    @PreAuthorize("hasRole('ROLE_SHOPMANAGER') or hasRole('ROLE_CUSTOMER')")
    @GetMapping("/{categoryId}")
    public ResultVO<FoodCategory> getCategoryById(@PathVariable Integer categoryId) {
        FoodCategory category = foodCategoryService.getCategoryById(categoryId);
        return ResultVOUtil.buildResult(ResultEnum.GET_SUCCESS,category);
    }

    // 分页列出所有食品类别
    @PreAuthorize("hasRole('ROLE_SHOPMANAGER') or hasRole('ROLE_CUSTOMER')")
    @GetMapping
    public ResultVO<FoodCategoryPageVO> listAllCategories(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        FoodCategoryPageVO categoryPage = foodCategoryService.listAllCategories(page, size);
        return ResultVOUtil.buildResult(ResultEnum.GET_SUCCESS,categoryPage);
    }

    @PreAuthorize("hasRole('ROLE_SHOPMANAGER')")
    @PostMapping("/image")
    public ResultVO<String> uploadDishImage(MultipartFile file) {
        return ResultVOUtil.buildResult
                (ResultEnum.POST_SUCCESS, aliYunOSSUtil.uploadFile(file, FileType.DISH_IMAGE).getUrl());
    }

}

